package com.kabu;

import java.util.LinkedList;
import java.util.List;

/**
 * 编译优化带来的有序性问题
 */
public class ThreadOrder {
    static ThreadOrder instance=null;
    //@Test(threadPoolSize = 100, invocationCount = 10, timeOut = 0)
    static void getInstance(){
        System.out.println(Thread.currentThread().getName());
        if(instance==null){
            synchronized(ThreadOrder.class){
                if(instance==null){
                    //指令重拍
                    instance=new ThreadOrder();
                }
            }
        }
    }
    public void print(){
        System.out.println(this);
    }
    public static void main(String []args) {
        for (int i = 0; i < 100; i++) {
            instance=null;
            instanceTest();
        }
    }

    private static void instanceTest() {
        List<Thread> threadList = new LinkedList<>();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(() -> {
                ThreadOrder.getInstance();
                instance.print();
            });
            threadList.add(thread);

        }
        for (Thread thread : threadList) {
            thread.start();
        }
    }

}
